using System;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

namespace JEngine.Framework
{
    

    public class DownTask
    {
       

        private static AcceptAllCertificate certificateHandler = new AcceptAllCertificate();

        private UnityWebRequest Request;

        public bool isCancel;

        private UniTaskCompletionSource<byte[]> tcs;

        public void Dispose()
        {
            this.Request?.Dispose();
            this.Request = null;
            this.isCancel = false;
        }


        public float Progress
        {
            get
            {
                if (Request == null)
                {
                    return 0;
                }

                return Request.downloadProgress;
            }
        }


        public void Stop()
        {
            isCancel = true;
        }

        private string UrlCheak(string url)
        {
            StringBuilder writeText = new StringBuilder();
            url = url.Replace(" ", "%20");
            if (!url.StartsWith("http"))
                writeText.Append("http://");
            writeText.Append(url);
            return writeText.ToString();
        }
        public async UniTask<byte[]> DownloadAsync(string url)
        {
            this.LogColor("开始下载");
            isCancel = false;
            tcs = UniTask<byte[]>.Create();
            url = UrlCheak(url);
            this.LogColor(url);
            Request = UnityWebRequest.Get(url);
            Request.certificateHandler = certificateHandler;
            //这里会出现一个警告提醒  提醒加上await
            //但是因为我想加入取消的逻辑  所以没有阻塞  这个警告是可以允许存在的
            Request.SendWebRequest();
            if (isCancel)
                tcs.TrySetException(new Exception($"request error: {this.Request.error}"));
           
            while (!Request.isDone)
            {
                if (isCancel)
                {
                    tcs.TrySetResult(default);
                    Dispose();
                    return await tcs.Task;
                }

                await UniTask.Yield();
            }
            if (Request.result != UnityWebRequest.Result.Success )
                tcs.TrySetException(new Exception($"request error: {this.Request.error}"));
            tcs.TrySetResult(Request.downloadHandler.data);
            this.LogColor("下载完毕");
            return await tcs.Task;
        }

        public async UniTask<Texture2D> DownTexture2D(string url)
        {
            isCancel = false;
            var tex = UniTask<Texture2D>.Create();
            url = UrlCheak(url);
            using (Request = UnityWebRequestTexture.GetTexture(url))
            {
                Request.certificateHandler = certificateHandler;
                Request.SendWebRequest();
             

                while (!Request.isDone)
                {
                    if (isCancel)
                    {
                        tex.TrySetResult(default);
                        Dispose();
                        return await tex.Task;
                    }

                    await UniTask.Yield();
                }
                if (Request.result != UnityWebRequest.Result.Success )
                {
                    Debug.LogError("下载图片路径：" + url);
                    Debug.LogError("下载图片错误：" + Request.error);
                }

                Texture2D tex2d = DownloadHandlerTexture.GetContent(Request);
                tex.TrySetResult(tex2d);
                this.LogColor("下载图片完毕");
                return   await tex.Task;
                 
            }
        }
    }

   
}